#include "headers/RegisterDialog.h"
#include <QMessageBox>
#include <QRandomGenerator>

RegisterDialog::RegisterDialog(AuthClient *authClient, EmailSender *emailSender, QWidget *parent)
    : QDialog(parent),
    ui(new Ui::RegisterDialog),
    m_authClient(authClient),
    m_emailSender(emailSender)
{
    ui->setupUi(this);
    connect(ui->getCodeBtn, &QPushButton::clicked, this, &RegisterDialog::onGetCodeClicked);
    connect(ui->registerBtn, &QPushButton::clicked, this, &RegisterDialog::onRegisterClicked);
    connect(m_authClient, &AuthClient::codeSent, this, &RegisterDialog::onCodeSent);
    connect(m_authClient, &AuthClient::registerResult, this, &RegisterDialog::onRegisterResult);
    connect(m_emailSender, &EmailSender::sendSuccess, this, &RegisterDialog::onEmailSendSuccess);
    connect(m_emailSender, &EmailSender::sendFailed, this, &RegisterDialog::onEmailSendFailed);
}

void RegisterDialog::onGetCodeClicked()
{
    m_email = ui->emailEdit->text().trimmed();
    if (m_email.isEmpty() || !m_email.contains("@") || !m_email.contains(".")) {
        QMessageBox::warning(this, "输入错误", "请输入有效邮箱地址");
        return;
    }
    int codeNum = QRandomGenerator::global()->bounded(900000) + 100000;
    QString code = QString("%1").arg(codeNum);
    m_emailSender->sendVerificationCode(m_email, code);
    m_authClient->requestVerificationCode(m_email);
}

void RegisterDialog::onRegisterClicked()
{
    QString password = ui->passwordEdit->text();
    QString confirmPwd = ui->confirmPwdEdit->text();
    QString code = ui->verificationCodeEdit->text().trimmed();

    if (password.isEmpty() || confirmPwd.isEmpty() || code.isEmpty() || code.length() != 6) {
        QMessageBox::warning(this, "输入错误", "请填写完整信息，验证码需为6位数字");
        return;
    }
    if (password != confirmPwd) {
        QMessageBox::warning(this, "输入错误", "两次密码不一致");
        return;
    }
    m_authClient->registerUser(m_email, password, code);
}

void RegisterDialog::onCodeSent(bool success)
{
    if (!success) {
        QMessageBox::warning(this, "失败", "验证码请求失败，请稍后再试");
    }
}

void RegisterDialog::onRegisterResult(bool success, const QString &message)
{
    if (success) {
        QMessageBox::information(this, "注册成功", message);
        accept();
    } else {
        QMessageBox::warning(this, "注册失败", message);
    }
}

void RegisterDialog::onEmailSendSuccess()
{
    QMessageBox::information(this, "提示", "验证码已发送至邮箱，请查收");
}

void RegisterDialog::onEmailSendFailed(const QString &error)
{
    QMessageBox::warning(this, "邮件发送失败", error);
}
